package cn.weekimwee.firstlineofcodeforkotlin.unit5

import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_unit5.*
import org.jetbrains.anko.startActivity

class Unit5Activity : BaseActivity() {
    lateinit var receiver: MyLocalReceiver
    lateinit var manager: LocalBroadcastManager
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_unit5)
        //本地广播的管理器
        manager = LocalBroadcastManager.getInstance(this)
        demo1.setOnClickListener {
            //跳转到一个测试有网没网的activity
            startActivity<Demo1Activity>()
            //普通广播
            sendOrderedBroadcast(Intent("cn.weekimwee.firstlineofcodeforkotlin.unit5.MY_BROADCAST"),null)
        }
        //本地广播接收器
        receiver = MyLocalReceiver()
        demo2.setOnClickListener {
            manager.sendBroadcast(Intent("cn.weekimwee.firstlineofcodeforkotlin.unit5.MY_LOCAL_BROADCAST"))
        }

        val intentFilter = IntentFilter().apply {
            addAction("cn.weekimwee.firstlineofcodeforkotlin.unit5.MY_LOCAL_BROADCAST")
        }
        //用管理器去注册  就是注册的本地的
        manager.registerReceiver(receiver,intentFilter)
        demo3.setOnClickListener {
            startActivity<Unit5_1Activity>()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        //解除注册
        manager.unregisterReceiver(receiver)
    }
}
